<?php 
error_reporting(E_ALL);

class Buyback_Helper_Search extends Zend_Controller_Action_Helper_Abstract{
	
	protected $view;
	
	public function preDispatch(){
		
		if (null === ($controller = $this->getActionController())) {
			return;
        }
        
        $this->handleSearch();
	}
	
	public function getView(){
		
		if (null !== $this->view) {
            return $this->view;
        }

        $controller = $this->getActionController();
        $view = $controller->view;
        if (!$view instanceof Zend_View_Abstract) {
            return;
        }
        $view->addScriptPath(APPLICATION_PATH . '/modules/buyback/views/scripts');
        $this->view = $view;
        return $view;
	}
	
	public function displayResult(array $itemList = array()){
	 	if (!$view = $this->getView()) {
            return;
        }

		$view->result = $view->partial('result.phtml', array(
            'itemList' => $itemList,
        ));
	}
	
	public function renderForm(Buyback_Form_Search $form){
		if (!$view = $this->getView()) {
            return;
        }

        $view->search = $view->partial('search.phtml', array(
            'form'  => $form
        ));
	}
	
	public function handleSearch(){
		$request = $this->getRequest();
		$form = new Buyback_Form_Search();
		
		if($request->isPost()){
			if($form->isValid($request->getPost())){
				$isbnListRaw = $form->isbnList->getValue();
				$isbnList = Custom_ConvertInput::getArray($isbnListRaw);
				$offer = new Buyback_Model_Offer($isbnList);
				$offer->createOffer();
				$this->displayResult($isbnList);
			}
		}	
		
		$this->renderForm($form);
	}
}